//
//  HYQBaseBridgeManager.m
//  HYQWebkit_Example
//
//  Created by zhuxingjian on 2018/8/20.
//  Copyright © 2018年 zxj1989. All rights reserved.
//

#import "HYQBaseBridgeManager.h"
#import "HYQMethdModel.h"
#import "HYQWebView.h"

#define HYQ_BRIDGE_CLASS_NAME           @"className"
#define HYQ_BRIDGE_CLASS_PROPERTY       @"property"


@interface HYQBaseBridgeManager ()

@property (nonatomic, strong) NSString *callbackMethod;

@end

@implementation HYQBaseBridgeManager

- (id)syncCallNative:(NSString *)method
{
    HYQMethdModel *methodModel = [self analysisMethod:method];
    if (methodModel) {
        __block id result = nil;
        IMP imp = [self methodForSelector:methodModel.sel];
        id (*func)(id, SEL, id) = (void *)imp;
        result = func(self, methodModel.sel, methodModel.methodParam);
        return result;
    }
    return @"no method";
}

- (void)asyncCallNative:(NSString *)method
{
    HYQMethdModel *methodModel = [self analysisMethod:method];
    methodModel.callback = @"clickIndex";
    self.callbackMethod = methodModel.callback;
    if (methodModel) {
        dispatch_async(dispatch_get_main_queue(), ^{
            IMP imp = [self methodForSelector:methodModel.sel];
            void (*func)(id, SEL, id) = (void *)imp;
            func(self, methodModel.sel, methodModel.methodParam);
        });
    }
}

- (HYQMethdModel *)analysisMethod:(NSString *)method
{
    NSLog(@"js调用原生方法：\n【%@】",method);
    if (!method.length) {
        NSLog(@"js调用原生未传参数");
        return nil;
    }
    NSDictionary *dic = [self stringToJSONObject:method];
    if (!dic) {
        NSLog(@"js调用原生参数解析失败");
        return nil;
    }
    HYQMethdModel *methodModel = [HYQMethdModel new];
    [methodModel setValuesForKeysWithDictionary:dic];
    if (methodModel.methodParam) {
        methodModel.methodName = [methodModel.methodName stringByAppendingString:@":"];
    }
    SEL sel = NSSelectorFromString(methodModel.methodName);
    if ([self respondsToSelector:sel]) {
        methodModel.sel = sel;
        return methodModel;
    }
    return nil;
}

- (void)print:(NSDictionary *)logInfo
{
    NSLog(@"***********【JS打印日志】**********\n%@\n***********【JS打印日志】**********",logInfo[@"methodParam"]);
}

- (void)pushViewController:(NSDictionary *)par
{
    dispatch_async(dispatch_get_main_queue(), ^{
        Class cls = NSClassFromString(par[HYQ_BRIDGE_CLASS_NAME]);
        UIViewController *vc = [[cls alloc] init];
        [vc setValuesForKeysWithDictionary:par[HYQ_BRIDGE_CLASS_PROPERTY]];
        [self.contentViewController.navigationController pushViewController:vc animated:YES];
    });
}

//- (void)popToViewController:(NSDictionary *)par
//{
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (par) {
//            NSString *tovc = par[HYQ_BRIDGE_CLASS_NAME];
//            NSArray *arr = self.contentViewController.navigationController.viewControllers;
//            for (NSInteger i = arr.count - 1; i >= 0; i --) {
//                UIViewController *vc = arr[i];
//                NSString *viewId = NSStringFromClass([vc class]);
//                if ([vc isKindOfClass:[HYQWebViewController class]]) {
//                    HYQWebViewController *webVC = (HYQWebViewController *)vc;
//                    viewId = webVC.viewId;
//                }
//                if ([viewId isEqualToString:tovc]) {
//                    [self.contentViewController.navigationController popToViewController:vc animated:YES];
//                    return;
//                }
//            }
//        }else {
//            [self.contentViewController.navigationController popViewControllerAnimated:par[@"animated"]];
//        }
//    });
//}

//- (void)callCurrentCallbackWithParam:(id)param;
//{
//    if (!self.callbackMethod) {
//        return;
//    }
//    NSMutableDictionary *method = [NSMutableDictionary dictionary];
//    method[@"methodName"] = self.callbackMethod;
//    if (param) {
//        method[@"methodParam"] = param;
//    }
//    HYQWebViewController *webVC = (HYQWebViewController *)self.contentViewController;
//
//    NSMutableString *methodName = [[NSMutableString alloc] initWithString:@"callJs"];
//
//    NSMutableString *paramter=[[NSMutableString alloc] initWithString:@"("];
//
//    //    if(param == nil){
//    //        [paramter appendString:@")"];
//    //    }else if([param isKindOfClass:[NSString class]]){//这种方式传过去的是个json字符串
//    //        [paramter appendFormat:@"'%@')",param];
//    //    }else if([param isKindOfClass:[NSNumber class]]){
//    //        [paramter appendFormat:@"%@)",param];
//    //    }else{//这种方式传过去的是json对象
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:method options:kNilOptions error:NULL];
//    NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    [paramter appendFormat:@"'%@')",result];
//    //    }
//    [methodName appendString:paramter];
//    if (![[NSThread currentThread] isMainThread]) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [webVC.webView stringByEvaluatingJavaScriptFromString:methodName];
//        });
//    }else {
//        [webVC.webView stringByEvaluatingJavaScriptFromString:methodName];
//    }
//}

- (NSDictionary *)stringToJSONObject:(NSString *)jsonString
{
    NSError *error = nil;
    NSData *data;
    data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                               options:NSJSONReadingAllowFragments
                                                                 error:&error];
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }
    return nil;
}

- (void)openNativePage:(NSString *)jsonString
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *par = [[self class] handleParam:jsonString callFromSel:_cmd];
        NSString *class = par[@"action_name"];
        NSDictionary *param = [self stringToJSONObject:par[@"action_param"]];
        UIViewController *vc = [[NSClassFromString(class) alloc] init];
        if (!vc) {
            NSLog(@"%@页面不存在",class);
            return;
        }
        if (param) {
            [vc setValuesForKeysWithDictionary:param];
        }
        [self.contentViewController.navigationController pushViewController:vc animated:YES];
    });
}

- (void)openWebPage:(NSString *)jsonString
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *par = [[self class] handleParam:jsonString callFromSel:_cmd];
        NSString *urlString = par[@"url"];
        if (!urlString) {
            NSLog(@"链接不存在");
            return;
        }
        NSLog(@"当前页面打开链接：%@",urlString);
        NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        [self.webView loadRequest:req];
    });
}

- (void)setTitle:(NSString *)title;
{
    self.contentViewController.title = title;
}

+ (NSDictionary *)handleParam:(NSString *)paramString callFromSel:(SEL)fromSel
{
    NSAssert(paramString, @"参数为传递");
#ifdef DEBUG
    NSLog(@"\n【JS开始调用原生方法】\n%@\n",NSStringFromSelector(fromSel));
#endif
    
    NSData *jsonData = nil;
    if([paramString dataUsingEncoding:NSASCIIStringEncoding]) {
        jsonData = [paramString dataUsingEncoding:NSASCIIStringEncoding];
    }else {
        jsonData = [paramString dataUsingEncoding:NSUTF8StringEncoding];
    }
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingAllowFragments
                                                          error:&err];
    if(err) {
#ifdef DEBUG
        NSLog(@"\n【JS调用原生参数解析失败】%@",err);
#endif
        return nil;
    }
#ifdef DEBUG
    NSLog(@"\n【JS调用原生参数解析完成】\n%@\n",dic);
#endif
    return dic;
}

@end
